package com.example.boot.security.handler;

import com.example.boot.pojo.result.Result;
import com.example.boot.utils.MyAuthenticationException;
import com.example.boot.utils.ResponseUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:  登录失败处理
 * @author: mhpy
 * @date 2022/8/7 10:05
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //响应编码
        response.setContentType("application/json;charset=utf-8");
        String message="login 失败";
        int code=20001;

        if (exception instanceof AccountExpiredException) {
            message="账户过期，登录失败";
        }if (exception instanceof BadCredentialsException) {
            message="账号密码错误bad";
        }if (exception instanceof CredentialsExpiredException) {
            message="密码过期，登录失败";
        }if (exception instanceof DisabledException) {
            message="账户禁用，登录失败";
        }if (exception instanceof LockedException) {
            message="账户被锁，登录失败";
        }if (exception instanceof InternalAuthenticationServiceException) {
            message="账户不存在，登录失败  in";
        }if (exception instanceof MyAuthenticationException){
            message="token失效 ------错误";
            code=20002;
        }

        ResponseUtil.out(response,Result.error(message).code(code));
    }
}
